<template>
  <div class="back-ground" id="background">
    <!-- 包裹图片的父容器 -->
    <div class="register-container" id="register-container" style="border-radius: 10px;box-shadow: 0 0 10px rgba(0,0,0,0.2)">
      <!-- 包裹图片和表单的父容器 -->
      <div id="wrapper" style="display: flex; flex-wrap: wrap; justify-content: center;">

        <div id="left-side">
          <div id="title" style="font-size: 30px; font-weight: bold; color: #333; margin-bottom: 20px;margin-top: 65px;padding-left: 35px">
            任务管理系统
          </div>
          <!-- 左侧图片 -->
          <div id="image-container" style="flex: 1; display: flex; justify-content: center;">
            <img src="../assets/images/register.jpg" alt="注册图片" class="register-image" id="register-image" />
          </div>
        </div>

        <!-- 右侧登录框 -->
        <div class="register-box" id="register-box">
          <div id="form-container" style="padding: 20px; background-color: #ffffff; margin-left: auto; margin-right: auto;">
            <el-form ref="formRef" :model="data.form" :rules="data.rules" class="register-form" id="register-form">
              <div class="form-header" id="form-header">
                注册 REGISTER
              </div>
              <el-form-item prop="role" id="form-item-role">
              </el-form-item>
              <el-form-item prop="username" id="form-item-username">
                <el-input size="large" v-model="data.form.username" placeholder="请输入用户名" prefix-icon="User" class="input-field" id="username-input"></el-input>
              </el-form-item>
              <el-form-item prop="password" id="form-item-password">
                <el-input show-password size="large" v-model="data.form.password" placeholder="请输入密码" prefix-icon="Lock" class="input-field" id="password-input"></el-input>
              </el-form-item>
              <el-form-item prop="confirmPassword" id="form-item-confirm-password">
                <el-input show-password size="large" v-model="data.form.confirmPassword" placeholder="请再次输入密码" prefix-icon="Lock" class="input-field" id="confirm-password-input"></el-input>
              </el-form-item>
              <el-form-item prop="name" id="form-item-name">
                <el-input size="large" v-model="data.form.name" placeholder="请输入您的姓名" prefix-icon="User" class="input-field" id="name-input"></el-input>
              </el-form-item>
              <el-form-item prop="email" id="form-item-email">
                <el-input size="large" v-model="data.form.email" placeholder="请输入您的邮箱" prefix-icon="Message" class="input-field" id="email-input"></el-input>
              </el-form-item>
              <el-form-item prop="captcha" id="form-item-captcha">
                <div class="role-control" style="display: flex;" id="captcha-container">
                  <el-input prefix-icon="check"
                            size="large"
                            v-model="data.form.captcha"
                            placeholder="请输入验证码"
                            style="width: 200px;"
                            class="input-field" id="captcha-input">
                  </el-input>
                  <div class="captcha-box" @click="refreshCaptcha" v-html="captchaText" id="captcha-box"></div>
                </div>
              </el-form-item>
              <div  class="role-control" id="role-control">
                <el-radio-group v-model="data.form.role" id="role-radio-group">
                  <el-radio value="1" label="管理员" id="role-admin">管理员</el-radio>
                  <el-radio value="0" label="员工" id="role-user">普通用户</el-radio>
                </el-radio-group>
              </div>
              <el-button @click="submitRegister" type="primary" size="large" class="submit-btn" id="submit-btn">注册</el-button>
              <div class="footer-links" id="footer-links">
                <router-link to="/login" class="footer-link" id="login-link">已有账号?登录</router-link>
              </div>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRegisterStore } from "@/store/register";
import { onMounted } from "vue";
import { router } from "@/router/index.js";
import { ElMessage } from "element-plus";

// 当前验证码
const currentCaptcha = ref('');
// 注册store
const registerStore = useRegisterStore();
// 验证码文本
const captchaText = ref('');

// 密码验证函数，确保密码一致
const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请再次确认密码'));
  } else if (value !== data.form.password) {
    callback(new Error('两次密码不一致'));
  } else {
    callback();
  }
};

// 定义表单数据和规则
const data = reactive({
  form: {
    role: '',
    username: '',
    password: '',
    confirmPassword: '',
    name: '',
    email: '',
    captcha: '',
  },
  rules: {
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 5, message: '账号最少5位', trigger: 'blur' },
        {max: 20, message: '账号最多20位', trigger: 'blur'}
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 8, message: '密码最少8位', trigger: 'blur' },
      {max: 20, message: '密码最多20位', trigger: 'blur'}
    ],
    confirmPassword: [
      { validator: validatePass, trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入您的姓名', trigger: 'blur' },
        { min: 2, message: '姓名最少2位', trigger: 'blur' },
        {max: 20, message: '姓名最多20位', trigger: 'blur'}
    ],
    email: [
      { required: true, message: '请输入您的邮箱', trigger: 'blur' },
      {
        message: '请输入有效的邮箱地址',
        trigger: 'blur'
      },
      {
        // 自定义验证规则，检查主机部分
        validator: (rule, value, callback) => {
          const emailPattern = /^[a-zA-Z0-9]{3,18}@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/;
          if (!emailPattern.test(value)) {
            return callback(new Error('请输入有效的邮箱地址'));
          }
          // 分割邮箱地址得到主机部分（整个域名部分）
          const domain = value.split('@')[1];
          if (domain) {
            // 检查主机部分（整个域名）长度和是否符合规则，这里设定主机部分整体合理长度范围是3-255个字符（可按需调整）
            const hostPattern = /^[a-zA-Z0-9.-]{3,255}$/;
            if (!hostPattern.test(domain)) {
              return callback(new Error('主机部分（域名）长度及格式不符合要求'));
            }
          }

          callback();
        },
        trigger: 'blur'
      }
    ],
    captcha: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
    ],
    role: [
      { required: true, message: '请选择角色', trigger: 'change' },
    ]
  }
});

// 生成验证码
const generateCaptcha = () => {
  const characters = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
  let result = '';
  for (let i = 0; i < 4; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  currentCaptcha.value = result;

  captchaText.value = result.split('').map(char => {
    const color = `rgb(${Math.random() * 150 + 50}, ${Math.random() * 150 + 50}, ${Math.random() * 150 + 50})`;
    const rotate = Math.random() * 30 - 15;
    return `<span style="color: ${color}; display: inline-block; transform: rotate(${rotate}deg);">${char}</span>`;
  }).join('');
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
};

// 页面加载时生成验证码
onMounted(() => {
  generateCaptcha();
});

const  formRef = ref()
// 提交注册表单
const submitRegister = () => {
  if (data.form.captcha.toLowerCase() !== currentCaptcha.value.toLowerCase()) {
    ElMessage.error('验证码错误');
    generateCaptcha();
    data.form.captcha = '';
    return;
  }
  formRef.value.validate((valid) => {
    if (valid) {
      // 验证通过，准备注册请求
      let jsonObj = JSON.stringify(data.form);
      registerStore.register(jsonObj, (res) => {
        if (res.code == 200) {
          ElMessage({
            message: '注册成功',
            type: 'success',
            plain: true,
          });
          setTimeout(() => router.push("/login"), 1000);
        } else {
          ElMessage({
            message: res.msg,
            type: 'error',
            plain: true,
          });
        }
      });
    } else {
      // 验证失败，提示用户
      ElMessage({
        message: '注册信息不完整，请检查输入',
        type: 'error',
        plain: true,
      });
      return false;
    }
  });
};
</script>


<style scoped>
.back-ground{
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;

}
/* 容器 */
.register-container {
  display: flex;
  align-items: center;
  overflow: hidden;
  justify-content: center;

  background-color: white;
  border-radius: 10px;


}

/* 图片样式 */
.register-image {
  width: 95%;

  height: auto;  /* 保证图片的高度自适应 */
  max-height:
      60%;

}

/* 右侧登录框 */
.register-box {
  width: 430px;
  max-width: 100%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
}

/* 表单样式 */
.register-form {
  width: 360px;
  height: auto;
  margin-top: 15px;
  padding: 10px;
  box-sizing: border-box;

}

.form-header {
  font-size: 24px;
  text-align: center;
  color: #1e1e7c;
  font-weight: bold;
  margin-bottom: 20px;
}

.input-field {
  width: 100%;
  margin: 0 auto;
}

.role-control {
  display: flex;
  justify-content: space-between;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  margin-top: 5px;
  font-size: 15px;
  letter-spacing: 2px;
}

/* 底部链接 */
.footer-links {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #0066bc;
  margin-top: 10px;
}

.footer-link {
  color: #0066bc;
}

/* 手机端适配 */
@media (max-width: 825px) {
  .register-container {
    flex-direction: column; /* 手机屏幕时图片和表单在垂直方向排列 */
  }

  /* 在手机端设置图片宽度为100% */
  .register-image {
    width: 250px;
    height: 250px;
    max-height: none;  /* 清除最大高度限制 */
  }

  .register-box {
    width: 90%;
    height: auto; /* 自动适应高度 */
  }

  .form-header {
    font-size: 20px;
  }

  .input-field {
    margin: 0;
  }

  .submit-btn {
    font-size: 14px;
  }

  .footer-links {
    flex-direction: column;
    align-items: center;
  }

  .footer-link {
    margin: 5px 0;
  }
}
.captcha-image {
  cursor: pointer;
  margin-right: 10px;
}
.captcha-box {
  margin-left: 10px;
  padding: 5px 10px;
  background: #f0f2f5;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
  font-size: 20px;
  font-family: 'Arial', sans-serif;
  letter-spacing: 3px;
  display: flex;
  align-items: center;
  min-width: 100px;
  height: 40px;
  justify-content: center;
}
</style>

